package com.example.room.mv;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.blankj.subutil.util.PinyinUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.subutil.util.StringUtils;
import com.example.room.entity.User;
import com.example.room.repository.UserRepository;
import com.example.room.UserWithOrders;

import java.util.List;

// 在 UserViewModel 或其他适当的位置
public class UserViewModel extends ViewModel {
    MutableLiveData<Long> insert = new MutableLiveData<>();

    @Deprecated
    public MutableLiveData<Long> getActiveResult() {
        return insert;
    }

    private final UserRepository userRepository;

    public UserViewModel(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 插入用户
    public void insertUser(User user) {
        if (user != null) {
            user.userNamePinyin = PinyinUtils.getPinyinFirstLetters(user.userName);
            LogUtils.v("【拼音】汉字转拼音(首字母)= " + user.userNamePinyin);
        }

        userRepository.insertUser(user);
    }

    // 获取指定用户及其所有订单信息
    public LiveData<UserWithOrders> getUserWithOrders(long userId) {
        return userRepository.getUserWithOrders(userId);
    }

    public LiveData<List<User>> searchUsers(String name, String namePinyin) {
        LogUtils.v("【数据库】模糊查询= " + name + "  " + namePinyin);

        return userRepository.searchUsers(name, namePinyin);
    }

    public LiveData<List<User>> searchUsers(String name) {
        LogUtils.v("【数据库】文本= " + name);
        String namePinyin = PinyinUtils.getPinyinFirstLetters(name);
        String nameSplit = StringUtils.concatenateStrings(name);
        LogUtils.v("【数据库】文本(拆分)= " + nameSplit);
        LogUtils.v("【数据库】首拼音= " + namePinyin);
        String namePinyinSplit = StringUtils.concatenateStrings(namePinyin);
        LogUtils.v("【数据库】首拼音(拆分)= " + namePinyinSplit);

        return userRepository.searchUsers(name, nameSplit, namePinyin, namePinyinSplit);
    }




    private MutableLiveData<List<User>> searchUsers = new MutableLiveData<>();
    public MutableLiveData<List<User>> getSearchUsers() {
        return searchUsers;
    }
    public LiveData<List<User>> searchUsers(final User user) {
        final String name = user.userName;

        LogUtils.v("【数据库】文本= " + name);
        String namePinyin = PinyinUtils.getPinyinFirstLetters(name);
        String nameSplit = StringUtils.concatenateStrings(name);
        LogUtils.v("【数据库】文本(拆分)= " + nameSplit);
        LogUtils.v("【数据库】首拼音= " + namePinyin);
        String namePinyinSplit = StringUtils.concatenateStrings(namePinyin);
        LogUtils.v("【数据库】首拼音(拆分)= " + namePinyinSplit);

        LiveData<List<User>> userList = userRepository.searchUsers(name, nameSplit, namePinyin, namePinyinSplit);
        //searchUsers.postValue(userList);

        return userList;
    }

}
